﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;

namespace Portal.Modules.ImageBrowser
{
  public partial class StateEditModuleSettings : Portal.StateBase.ModuleState
  {
    DataAccessor _dataAccessor;
    CacheAgent _cacheAgent;

    string _SampleSource = "~/PortalImages/SamplePhoto.jpg";
    string _SampleTarget = "_samplePhoto.jpg";

    protected void Page_Load(object sender, EventArgs e)
    {
      _dataAccessor = new DataAccessor(Document);
      _cacheAgent = new CacheAgent(_dataAccessor);

      _tabBasic.HeaderText = Portal.Api.Language.GetText(this, "TabBasicTitle");
      _tabThumbnails.HeaderText = Portal.Api.Language.GetText(this, "TabThumbnailsTitle");
      _tabPreview.HeaderText = Portal.Api.Language.GetText(this, "TabPreviewTitle");
      _virtualPathEdit_WatermarkExtender.WatermarkText = Portal.Api.Language.GetText(this, "PictureVirtualDirectoryWM");

      if (!ControlPostback)
      {
        var cfg = _dataAccessor.Config;
        _virtualPathEdit.Text = cfg.PictureVirtualPath;

        // Set the current values from the configuration for the Thumbnails.
        _thumbSizeEdit.Text = cfg.ThumbCfg.MaxSize.ToString();
        if (cfg.ThumbnailCount > 0)
          _thumbCountEdit.Text = cfg.ThumbnailCount.ToString();
        else
          _thumbCountEdit.Text = "0";
        _thumbJpegQualitySlider.Text = cfg.ThumbCfg.JpegQuality.ToString();
        _thumbWithShadowCheck.Checked = cfg.ThumbCfg.HasShadow;
        _thumbShadowWithEdit.Text = cfg.ThumbCfg.ShadowWidth.ToString();
        _thumbShadowColor.Text = GetHtmlColor(cfg.ThumbCfg.ShadowColor);
        _thumbTransparencySlider.Text = ((int) System.Math.Round(cfg.ThumbCfg.ShadowTransparency * 100.0)).ToString();
        _thumbBgColor.Text = GetHtmlColor(cfg.ThumbCfg.BackgroundColor);
        _thumbBorderWithEdit.Text = cfg.ThumbCfg.BorderWidth.ToString();
        _thumbBorderColor.Text = GetHtmlColor(cfg.ThumbCfg.BorderColor);
        _thumbSoftShadowCheck.Checked = cfg.ThumbCfg.SoftShadow;

        EnableThumbShadow(cfg.ThumbCfg.HasShadow);
        UpdateThumbPreview();


        // Set the current values from the configuration for the Preview.
        cfg = _dataAccessor.Config;
        _previewSizeEdit.Text = cfg.PreviewCfg.MaxSize.ToString();
        _previewJpegQualitySlider.Text = cfg.PreviewCfg.JpegQuality.ToString();
        _previewWithShadowCheck.Checked = cfg.PreviewCfg.HasShadow;
        _previewShadowWithEdit.Text = cfg.PreviewCfg.ShadowWidth.ToString();
        _previewShadowColor.Text = GetHtmlColor(cfg.PreviewCfg.ShadowColor);
        _previewTransparencySlider.Text = ((int)System.Math.Round(cfg.PreviewCfg.ShadowTransparency * 100.0)).ToString();
        _previewBgColor.Text = GetHtmlColor(cfg.PreviewCfg.BackgroundColor);
        _previewSoftShadowCheck.Checked = cfg.PreviewCfg.SoftShadow;

        EnablePreviewShadow(cfg.PreviewCfg.HasShadow);
        UpdatePreviewPreview();
      }
    }


    protected static string GetHtmlColor(Color color)
    {
      return ColorTranslator.ToHtml(color).TrimStart('#');
    }

    protected void OnSave(object sender, EventArgs e)
    {
      bool changed = false;
      bool updateThumbnails = false;
      bool updatePreview = false;
      bool updatePreviewShadow = false;
      
      
      var cfg = _dataAccessor.Config;

      // If the filepath has changed, then update every cached image.
      if(0 != string.Compare(_virtualPathEdit.Text, _dataAccessor.Config.PictureVirtualPath, true))
      {
        cfg.PictureVirtualPath = _virtualPathEdit.Text;
        updatePreview = true;
        updateThumbnails = true;
        changed = true;
      }

      // Update the Thumbnail fonfiguration.
      int number = -1;
      int.TryParse(_thumbCountEdit.Text, out number);
      if (number < 1)
        number = -1;
      if (number != cfg.ThumbnailCount)
      {
        cfg.ThumbnailCount = number;
        changed = true;
      }

      var thumbnailCfg = GetCurrentThumbnailCfg();
      if (!thumbnailCfg.Equals(cfg.ThumbCfg))
      {
        cfg.ThumbCfg = thumbnailCfg;
        updateThumbnails = true;
        changed = true;
      }

      // Update the Preview Configuration.
      var previewCfg = GetCurrentPreviewCfg();
      if (previewCfg.JpegQuality != cfg.PreviewCfg.JpegQuality
        ||previewCfg.MaxSize != cfg.PreviewCfg.MaxSize)
      {
        updatePreview = true;
        changed = true;
      }
      if( previewCfg.HasShadow != cfg.PreviewCfg.HasShadow
        || previewCfg.ShadowWidth != cfg.PreviewCfg.ShadowWidth
        || previewCfg.ShadowTransparency != cfg.PreviewCfg.ShadowTransparency
        || previewCfg.ShadowColor != cfg.PreviewCfg.ShadowColor
        || previewCfg.BackgroundColor != cfg.PreviewCfg.BackgroundColor
        || previewCfg.SoftShadow != cfg.PreviewCfg.SoftShadow)
      {
        updatePreviewShadow = true;
        changed = true;
      }
      if (updatePreview || updatePreviewShadow)
        cfg.PreviewCfg = previewCfg;


      if (changed)
      {
        // Increment the Configuration Version.
        ++cfg.ConfigVersion;
        Document.WriteConfig(cfg);
      }
      
      if(updateThumbnails)
        _cacheAgent.UpdateThumbnailCache();

      if (updatePreview)
        _cacheAgent.UpatePreviewCache(updatePreviewShadow);

      if (updatePreviewShadow)
        _cacheAgent.UpdatePreviewShadowParts();

      RedirectBack();
    }

    protected static bool GetFromHtmlColor(string htmlColor, out Color color)
    {
      try
      {
        color = ColorTranslator.FromHtml("#" + htmlColor);
        return true;
      }
      catch 
      {
        color = Color.Empty;
        return false; 
      }
    }

    protected void OnCancel(object sender, EventArgs e)
    {
      RedirectBack();
    }
    protected void OnThumbWithShadow(object sender, EventArgs e)
    {
      EnableThumbShadow(_thumbWithShadowCheck.Checked);
    }

    protected void OnPreviewWithShadow(object sender, EventArgs e)
    {
      EnablePreviewShadow(_thumbWithShadowCheck.Checked);
    }

    protected void EnableThumbShadow(bool enable)
    {
      _thumbShadowWidth.Enabled = enable;
      _thumbShadowWithEdit.Enabled = enable;
      _thumbShadowWidthPxLbl.Enabled = enable;
      _thumbShadowColorLbl.Enabled = enable;
      _thumbShadowColor.Enabled = enable;
      _thumbShadowColorSample.Enabled = enable;
      _thumbTransparency.Enabled = enable;
      _thumbTransparencySlider_SliderExtender.Enabled = enable;
      _thumbTransparencySlider.Visible = enable;
      _thumbTransparencyEdit.Enabled = enable;
      _thumbBgColorLbl.Enabled = enable;
      _thumbBgColor.Enabled = enable;
      _thumbBgColorSample.Enabled = enable;
      _thumbBorderWidthLbl.Enabled = enable;
      _thumbBorderWithEdit.Enabled = enable;
      _thumbBorderWidthPxLbl.Enabled = enable;
      _thumbBorderColorLbl.Enabled = enable;
      _thumbBorderColor.Enabled = enable;
      _thumbBorderColorSample.Enabled = enable;
      _thumbSoftShadowLbl.Enabled = enable;
      _thumbSoftShadowCheck.Enabled = enable;
    }

    protected void EnablePreviewShadow(bool enable)
    {
      _previewShadowWidth.Enabled = enable;
      _previewShadowWithEdit.Enabled = enable;
      _previewShadowWidthPxLbl.Enabled = enable;
      _previewShadowColorLbl.Enabled = enable;
      _previewShadowColor.Enabled = enable;
      _previewShadowColorSample.Enabled = enable;
      _previewTransparency.Enabled = enable;
      _previewTransparencySlider_SliderExtender.Enabled = enable;
      _previewTransparencySlider.Visible = enable;
      _previewTransparencyEdit.Enabled = enable;
      _previewBgColorLbl.Enabled = enable;
      _previewBgColor.Enabled = enable;
      _previewBgColorSample.Enabled = enable;
      _previewSoftShadowLbl.Enabled = enable;
      _previewSoftShadowCheck.Enabled = enable;
    }


    private ImageBrowserConfig.ImageCfg GetCurrentThumbnailCfg()
    {
      var cfg = new ImageBrowserConfig.ImageCfg();
      int.TryParse(_thumbSizeEdit.Text, out cfg.MaxSize);
      if (cfg.MaxSize < 10)
        cfg.MaxSize = 10;
      byte.TryParse(_thumbJpegQualitySlider.Text, out cfg.JpegQuality);
      cfg.HasShadow =_thumbWithShadowCheck.Checked;
      int.TryParse(_thumbShadowWithEdit.Text, out cfg.ShadowWidth);
      
      Color color;
      if (GetFromHtmlColor(_thumbShadowColor.Text, out color))
        cfg.ShadowColor = color;

      byte transparency = 50;
      if(byte.TryParse(_thumbTransparencySlider.Text, out transparency))
        cfg.ShadowTransparency = transparency / 100.0;

      if (GetFromHtmlColor(_thumbBgColor.Text, out color))
        cfg.BackgroundColor = color;

      int.TryParse(_thumbBorderWithEdit.Text, out cfg.BorderWidth);

      if (GetFromHtmlColor(_thumbBorderColor.Text, out color))
        cfg.BorderColor = color;

      cfg.SoftShadow = _thumbSoftShadowCheck.Checked;

      return cfg;
    }

    private ImageBrowserConfig.ImageCfg GetCurrentPreviewCfg()
    {
      var cfg = new ImageBrowserConfig.ImageCfg();
      int.TryParse(_previewSizeEdit.Text, out cfg.MaxSize);
      if (cfg.MaxSize < 10)
        cfg.MaxSize = 10;
      byte.TryParse(_previewJpegQualitySlider.Text, out cfg.JpegQuality);
      cfg.HasShadow = _previewWithShadowCheck.Checked;
      int.TryParse(_previewShadowWithEdit.Text, out cfg.ShadowWidth);

      Color color;
      if (GetFromHtmlColor(_previewShadowColor.Text, out color))
        cfg.ShadowColor = color;

      byte transparency = 50;
      if (byte.TryParse(_previewTransparencySlider.Text, out transparency))
        cfg.ShadowTransparency = transparency / 100.0;

      if (GetFromHtmlColor(_previewBgColor.Text, out color))
        cfg.BackgroundColor = color;

      cfg.BorderWidth = 0;
      cfg.BorderColor = Color.Black;

      cfg.SoftShadow = _previewSoftShadowCheck.Checked;

      return cfg;
    }

    private void UpdateThumbPreview()
    {
      try
      {
        string sourcePath = Request.MapPath(_SampleSource);
        string targetPath = _cacheAgent.GetThumbnailCachePath(_SampleTarget);
        ImageUtility utility = new ImageUtility(_dataAccessor.Config);
        var cfg = GetCurrentThumbnailCfg();
        // Limit the size of the picture.
        if (cfg.MaxSize > 150)
        {
          cfg.MaxSize = 150;
          _thumbSmallerPreview.Visible = true;
        }
        else
          _thumbSmallerPreview.Visible = false;

        utility.CreateImage(sourcePath, targetPath, cfg, cfg.HasShadow);
        string vPath = _cacheAgent.GetThumbnailVirtualCachePath(_SampleTarget, false);
        // Add a random string to the url, to prevent caching.
        _previewThumbnailImg.ImageUrl = vPath + "?id=" + Guid.NewGuid().ToString();
      }
      catch { };
    }


    private void UpdatePreviewPreview()
    {
      try
      {
        string sourcePath = Request.MapPath(_SampleSource);
        string targetPath = _cacheAgent.GetPreviewCachePath(_SampleTarget);
        ImageUtility utility = new ImageUtility(_dataAccessor.Config);
        var cfg = GetCurrentPreviewCfg();

        // Limit the size of the picture.
        if (cfg.MaxSize > 150)
        {
          cfg.MaxSize = 150;
          _previewSmallerPreview.Visible = true;
        }
        else
          _previewSmallerPreview.Visible = false;

        utility.CreateImage(sourcePath, targetPath, cfg, cfg.HasShadow);
        string vPath = _cacheAgent.GetPreviewVirtualCachePath(_SampleTarget, false);
        // Add a random string to the url, to prevent caching.
        _previewPreviewImg.ImageUrl = vPath + "?id=" + Guid.NewGuid().ToString();
      }
      catch { };
    }


    protected void _updateThumbnailPreview_Click(object sender, EventArgs e)
    {
      UpdateThumbPreview();
    }

    protected void _updatePreviewPreview_Click(object sender, EventArgs e)
    {
      UpdatePreviewPreview();
    }
}
}